'use strict';
const { Service } = require('egg');

class UserService extends Service {

    async create(payload) {
        const { ctx } = this;
        var users = await this.app.mysql.select('user', {
            where: { mobile: payload.mobile }
        });

        if (users.length > 0) {
            console.log('mobile already exists');
            ctx.throw(400, 'mobile already exists');
        }

        payload.password = await ctx.genHash(payload.password);
        const result = await this.app.mysql.insert('user', {
            mobile: payload.mobile,
            password: payload.password,
            name: payload.name || "",
            createdAt: this.app.mysql.literals.now
        });

        if (result.affectedRows === 1) {
            users = await this.app.mysql.select('user', {
                where: { mobile: payload.mobile }
            });
            const userId = users[0].id;
            const token = ctx.helper.token(ctx, userId);
            return { 'token': token };
        }
        return null;
    }

    async login(payload) {
        const users = await this.app.mysql.select('user', {
            where: { mobile: payload.mobile }
        });
        if (users.length === 0) {
            this.ctx.throw(404, 'user not found')
        }
        let verifyPsw = await this.ctx.compare(payload.password, users[0].password)
        if (!verifyPsw) {
            this.ctx.throw(404, 'user password is error')
        }
        const userId = users[0].id;
        const token = this.ctx.helper.token(this.ctx, userId);
        return { 'token': token };
    }

    async update(payload) {
        const _id = this.ctx.state.user.data._id;
        const users = await this.app.mysql.select('user', {
            where: { id: _id }
        });
        if (users.length === 0) {
            this.ctx.throw(404, 'user not found')
        }
        var row = { id: _id };
        if (payload.name) {
            row = { ...row, name: payload.name };
        }
        if (payload.birthday) {
            row = { ...row, birthday: payload.birthday };
        }
        if (payload.gender) {
            row = { ...row, gender: Number(payload.gender) || 3 };
        }
        if (payload.avatar) {
            row = { ...row, avatar: payload.avatar };
        }
        const result = await this.app.mysql.update('user', row);
        const updateSuccess = result.affectedRows === 1;
        return updateSuccess;
    }
}

module.exports = UserService;